package com.app.island.cash.utilstools

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import com.appsflyer.AppsFlyerLib
import com.app.island.cash.Applications
import okhttp3.internal.and
import java.net.NetworkInterface
import java.net.SocketException
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.*

object SystemUtils {
    fun encode(data: String): String {
        return try {
            val digest = MessageDigest.getInstance("MD5")
            digest.update(data.toByteArray())
            bytes2Hex(digest.digest())
        } catch (e: Exception) {
            e.printStackTrace()
            data
        }
    }

    private fun bytes2Hex(bts: ByteArray): String {
        var des: String = ""
        var tmp: String? = null
        for (i in bts.indices) {
            tmp = Integer.toHexString(bts[i] and 0xFF)
            if (tmp.length == 1) {
                des += "0"
            }
            des += tmp
        }
        return des
    }

    val versionCode: String
        get() {
            var versionCode = "1"
            var packageManager: PackageManager? = null
            var packInfo: PackageInfo? = null
            try {
                packageManager = Applications.mContext!!.packageManager
                packInfo = packageManager.getPackageInfo(Applications.mContext!!.packageName, 0)
                versionCode = packInfo.versionCode.toString()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return versionCode
        }
    @JvmStatic
    val serialNumber: String
        get() {
            var hashCode = UUID.randomUUID().toString().hashCode()
            if (hashCode < 0) {
                hashCode = -hashCode
            }
            val sdf = SimpleDateFormat("yyyyMMdd")
            return sdf.format(Date()).substring(2, 8) + String.format(
                "%010d",
                *arrayOf<Any>(Integer.valueOf(hashCode))
            )
        }

    /**
     * 获得IMEI号
     */
    fun getIMEI(context: Context?): String {
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                return AppsFlyerLib.getInstance().getAppsFlyerUID(context)
            }
            val tm = context!!.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            if (tm != null) {
                tm.deviceId
            } else {
                AppsFlyerLib.getInstance().getAppsFlyerUID(context)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            AppsFlyerLib.getInstance().getAppsFlyerUID(context)
        }
    }

    @JvmStatic
    fun getAndroidID(context: Context): String {
        return Settings.System.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
    }

    fun macAddress(): String {
        var address = ""
        // 把当前机器上的访问网络接口的存入 Enumeration集合中
        var interfaces: Enumeration<NetworkInterface>? = null
        try {
            interfaces = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val netWork = interfaces.nextElement()
                // 如果存在硬件地址并可以使用给定的当前权限访问，则返回该硬件地址（通常是 MAC）。
                val by = netWork.hardwareAddress
                if (by == null || by.size == 0) {
                    continue
                }
                val builder = StringBuilder()
                for (b in by) {
                    builder.append(String.format("%02X:", b))
                }
                if (builder.length > 0) {
                    builder.deleteCharAt(builder.length - 1)
                }
                val mac = builder.toString()
                // 从路由器上在线设备的MAC地址列表，可以印证设备Wifi的 name 是 wlan0
                if (netWork.name == "wlan0") {
                    address = mac
                }
            }
        } catch (e: SocketException) {
            e.printStackTrace()
        }
        return address
    }

    /**
     * 32位加密补零
     *
     * @param bts
     * @return
     */
    private fun buLingValue(bts: ByteArray): String {
        var des: String = ""
        var tmp: String? = null
        for (i in bts.indices) {
            tmp = Integer.toHexString(bts[i] and 0xFF)
            if (tmp.length == 1) {
                des += "0"
            }
            des += tmp
        }
        return des
    }

    fun md5(data: String): String {
        return try {
            val digest = MessageDigest.getInstance("MD5")
            digest.update(data.toByteArray())
            buLingValue(digest.digest())
        } catch (e: Exception) {
            e.printStackTrace()
            data
        }
    }

    /**
     * 获得wifi的IP地址
     */
    private fun getWIFIIP(context: Context): Int {
        // 获取wifi服务
        val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        // 判断wifi是否开启
        if (!wifiManager.isWifiEnabled) {
            wifiManager.isWifiEnabled = true
        }
        val wifiInfo = wifiManager.connectionInfo
        return wifiInfo.ipAddress
    }

    /**
     * 整型IP地址转成String的
     */
    private fun intToIP(IPAddress: Int): String {
        return (IPAddress and 0xFF).toString() + "." + (IPAddress shr 8 and 0xFF) + "." + (IPAddress shr 16 and 0xFF) + "." + (IPAddress shr 24 and 0xFF)
    }

    fun getVersionName(context: Context): String {
        // 默认为1.0
        var ret_val = "1.0"
        var manager: PackageManager? = null
        var info: PackageInfo? = null
        try {
            manager = context.packageManager
            info = manager.getPackageInfo(context.packageName, 0)
            ret_val = info.versionName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ret_val
    }

    val versionName: String
        get() = getVersionName(Applications.mContext!!)

    /**
     * 获取数据网络的IP地址
     */
    private val gPRSIP: String
        private get() {
            try {
                val en = NetworkInterface.getNetworkInterfaces()
                while (en.hasMoreElements()) {
                    val networkInterface = en.nextElement()
                    val addresses = networkInterface.inetAddresses
                    while (addresses.hasMoreElements()) {
                        val inetAddress = addresses.nextElement()
                        if (!inetAddress.isLoopbackAddress) {
                            return inetAddress.hostAddress.toString()
                        }
                    }
                }
            } catch (e: SocketException) {
                e.printStackTrace()
            }
            return ""
        }
    val iP: String
        get() {
            val WIFI_IP = getWIFIIP(Applications.mContext!!)
            val GPRS_IP = gPRSIP
            var ip = "0.0.0.0"
            if (WIFI_IP != 0) {
                ip = intToIP(WIFI_IP)
            } else if (!TextUtils.isEmpty(GPRS_IP)) {
                ip = GPRS_IP
            }
            return ip
        }
}